<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-05-10
 * @Time: 15:24
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： DynamicLike.php
 */
namespace app\api\model\dynamic;

use think\Db;
use think\Log;
use think\Model;

class DynamicLike extends Model {
    protected $table = 'dynamic_like';

    /**
     * likeStatus
     * 点赞状态
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param int $uid 用户id
     * @param int $id 动态id
     * @return int
     */
    public static function likeStatus($uid, $id)
    {
        $data = self::where('dynamic_id', $id)->where('user_id', $uid)->count();

        $result = $data?1:0;

        return $result;
    }

    /**
     * liked
     * 动态点赞
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param int $id 动态id
     * @param int $uid 用户id
     * @return bool
     */
    public static function createLiked($id, $uid)
    {
        $status = self::likeStatus($uid, $id);

        Db::startTrans();
        try {
            if ($status) {
                // 删除已有点赞记录
                Db::query("delete from dynamic_like where dynamic_id=:dynamic_id and user_id=:user_id", ['dynamic_id'=>$id, 'user_id'=>$uid]);

                // 更新问答点赞统计数据
                DynamicM::updateLikeCount($id, 'minus');
            } else {
                // 新增点赞记录
                Db::query("insert into dynamic_like (dynamic_id, user_id) values ({$id}, {$uid})");

                // 更新问答点赞统计数据
                DynamicM::updateLikeCount($id, 'plus');
            }

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Log::error('动态点赞【error】：'.$e->getMessage());

            Db::rollback();

            return false;
        }
    }
}